package com.seguriapp.common.security;

import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import com.seguriapp.entities.MenuLink;

public class SeguriAppUser extends User {

  private SeguriAppSession sesion;

  private static final long serialVersionUID = -6967931232077006904L;
  private static final Logger LOGGER = Logger.getLogger(SeguriAppAuthenticationProvider.class);

  public SeguriAppUser(final String username, final String password, final Collection<GrantedAuthority> authorities, final SeguriAppSession session) {
    super(username, password, true, true, true, true, authorities);
    this.sesion = session;
  }

  public static SeguriAppUser getSeguriAppSecureUser() {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOGGER.info(auth);
    if (auth == null || auth instanceof AnonymousAuthenticationToken) {
      return null;
    }
    return (SeguriAppUser) auth.getPrincipal();
  }

  public SeguriAppSession getSeguriAppSession() {
    return (SeguriAppSession) sesion;
  }

  public com.seguriapp.entities.User getSeguriAppUser() {
    return (com.seguriapp.entities.User) sesion.get(SeguriAppSession.Key.User);
  }

  public Long getLastAlertId() {
    return (Long) sesion.get(SeguriAppSession.Key.LastAlertId);
  }

  public Long getLastComplaintId() {
    return (Long) sesion.get(SeguriAppSession.Key.LastComplaintId);
  }

  @SuppressWarnings("unchecked")
  public List<MenuLink> getMenuLinks() {
    return (List<MenuLink>) sesion.get(SeguriAppSession.Key.MenuLinks);
  }

}
